package com.levi.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * Gateway限流规则配置类
 */
@Configuration
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    /**
     * 限流异常处理器
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    /**
     * 限流过滤器
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        // By default the order is HIGHEST_PRECEDENCE
        return new SentinelGatewayFilter();
    }

    /**
     * 容器初始化时候执行该方法
     */
    @PostConstruct
    public void doInit() {
        //加载网关限流规则
        initGatewayRules();
        //加载自定义限流异常处理器
        initBlockHandler();
    }


    /**
     * 网关限流规则
     */
    private void initGatewayRules() {
        HashSet<GatewayFlowRule> rules = new HashSet<GatewayFlowRule>();

        /**
         * resource :资源名称 ，可以是网关中的routes名称/id，也可以时自定义API分组名称
         * count  :限流阈值
         * setIntervalSec:统计时间窗口，单位是秒
         *
         * 60秒内只能访问3次   超过3次就会报 Blocked by Sentinel: ParamFlowException异常
         */

//        rules.add(new GatewayFlowRule("service-product")
//                .setCount(3)
//                .setIntervalSec(60));

        //添加分组限流规则，和 initCustomizedApis()方法一起使用, 不同api限流规则不同。
        rules.add(new GatewayFlowRule("product-api")
                .setCount(3)
                .setIntervalSec(60));
        rules.add(new GatewayFlowRule("order-api")
                .setCount(5)
                .setIntervalSec(60));
        GatewayRuleManager.loadRules(rules);
        initCustomizedApis();
    }

    /**
     * 自定义限流异常处理器    替代 Blocked by Sentinel: ParamFlowException异常
     */
    private void initBlockHandler() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String, String> map = new HashMap<>();

                map.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
                map.put("message", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(map));
            }
        };
        //加载自定义限流异常处理器
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    /**
     * 自定义API分组限流  不同的组限流规则不同
     */
    private void initCustomizedApis(){
        Set<ApiDefinition> definitions = new HashSet<>();
        //product-api组
        ApiDefinition api1 = new ApiDefinition("product-api")
                .setPredicateItems(new HashSet<ApiPredicateItem>(){{
                    add(new ApiPathPredicateItem().setPattern("/service-product/product/*")   //对product下所有路径进行限流
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        //order-api组
        ApiDefinition api2 = new ApiDefinition("order-api")
                .setPredicateItems(new HashSet<ApiPredicateItem>(){{
                    add(new ApiPathPredicateItem().setPattern("/service-order/order/index"));  // 对/order/index/进行限流
                }});
        definitions.add(api1);
        definitions.add(api2);
        //加载限流分组
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }


}
